const log4js      = require('../../data/log');
const logger      = log4js.getLogger('info');
const server      = require('../../sip/server');
const http        = require('http');
const constants   = require('../../data/constants');
const fs          = require('fs');
const request     = require("request");
const { fstat }   = require('fs');
const settingModel= require('../../model/setting');
var ffmpeg        = require('fluent-ffmpeg');

let Media={};

Media.ports={ };
/**
 * 没有首页
 * @param {*} req 
 * @param {*} res 
 */
Media.index = function (req, res){
    // 处理逻辑 ...
    res.send('NOT IMPLEMENTED: index');
}

Media.onStreamNotFound=function(req,res){
    logger.info('onStreamNotFound',req.body);
    res.send({'code':0,'msg':'success'});
};
Media.onFlowReport=function(req,res){
    logger.info('onFlowReport',req.body);
    res.send({'code':0,'msg':'success'});
};
Media.onServerStarted=function(req,res){
    logger.info('onServerStarted',req.body);
    res.send({'code':0,'msg':'success'});
};
Media.onStreamNoneReader=function(req,res){
    logger.info('onStreamNoneReader',req.body);
    /**
{
  mediaServerId: 'NQZSziqcnLJjV65M',
  app: 'rtp',
  schema: 'rtmp',
  stream: 'v_34020000001320000002_34020000001310000006',
  vhost: '__defaultVhost__'
}
     */
    let stream = req.body.stream.split('_');

    server.bye(stream[1],stream[2],(ret)=>{
        if(ret){
            res.send({'code':0,'msg':'success'});
        }else{
            res.send({'code':1,'msg':'通道未注册成功'});
        }
    });
};
Media.onPlay=function(req,res){

    // 获取一个port
    Media.openRtpServer({body:{stream_id:req.body.stream}},(res1)=>{
        // 发invite请求
        let stream = req.body.stream.split('_');
        logger.info(res1);
        if(res1.code==-300){
            // 流已经存在，去查找一下
            Media.listRtpServer().then((rows)=>{
                let port=0;
                for(var s in rows.data){
                    if(rows.data[s].stream_id == req.body.stream){
                        port = rows.data[s].port;
                        break;
                    }
                }
                if(port>0){
                    server.invite(stream[1],stream[2],port,(ret)=>{
                        if(ret){
                            res.send({'code':0,'msg':'success'});
                        }else{
                            res.send({'code':1,'msg':'通道未注册成功'});
                        }
                    });
                }
            });
        }else{
            // 分配新端口
            server.invite(stream[1],stream[2],res1.port,(ret)=>{
                if(ret){
                    res.send({'code':0,'msg':'success'});
                }else{
                    res.send({'code':1,'msg':'通道未注册成功'});
                }
            });
        }
    });
};
Media.onHttpAccess=function(req,res){
    res.send({
        'code':0,
        'err':'',
        path:req.body.path,
        second:600, 
        mediaServerId:req.body.mediaServerId
    });
};
Media.onStreamChanged=function(req,res){
    res.send({'code':0,'msg':'success'});
};
Media.onPublish=function(req,res){
    res.send({'code':0,'msg':'success'});
};
/**
 * 调用zlmediaKit的 /index/api/openRtpServer接口 
 * */ 
Media.openRtpServer=function(req,callback){
    let url = constants.zlmedia.url + 'index/api/openRtpServer';
    // 选取一个空余端口号
    let max = constants.zlmedia.rtpPort[1];
    let min = constants.zlmedia.rtpPort[0];
    if(!this.ports.index) this.ports.index = min-1;
    
    let port;
    if(this.ports[req.body.stream_id]){
        port = this.ports[req.body.stream_id];
    }else{
        this.ports.index++;
        port = this.ports.index;
        this.ports[req.body.stream_id] = port;
    }
    logger.info('这时ports',this.ports);
    if(port>max){
        logger.error('没有可用端口了');
    }else{
        let param ="?port=" + port + "&enable_tcp=1&stream_id=" + req.body.stream_id;
        logger.info(url+param);
        http.get(url + param ,(res)=>{
            var html="";
            res.on("data",(data)=>{
                html += data;
            });
            res.on("end",()=>{
                callback(JSON.parse(html));
            });
        }).on('error',(e)=>{
            logger.error(e);
        });
    }
};
/**
 * 释放所有rtp资源
 */
Media.resetRtpServer=function(){
    Media.listRtpServer().then((list)=>{
        for(var i in list.data){
            let stream=list.data[i].stream_id;
            Media.closeRtpServer(stream);
        }
    });
};
/**
 * 调用zlmediaKit的 /index/api/closeRtpServer 
 * */ 
Media.closeRtpServer=function(stream){
    let url = constants.zlmedia.url + 'index/api/closeRtpServer';
    let param ="?port=0&enable_tcp=false&stream_id=" + stream;
    http.get(url + param ,(res)=>{
        var html="";
        res.on("data",(data)=>{
            html += data;
        });
        res.on("end",()=>{
            console.log(JSON.parse(html));
        });
    }).on('error',(e)=>{
        logger.error(e);
    });
};
/**
 * 调用zlmediaKit的 /index/api/listRtpServer 
 * */ 
Media.listRtpServer=function(){
    let p=new Promise(function(resolve,reject){
        let url = constants.zlmedia.url + 'index/api/listRtpServer';
        let param ="?";
        http.get(url + param ,(res)=>{
            var html="";
            res.on("data",(data)=>{
                html += data;
            });
            res.on("end",()=>{
                resolve(JSON.parse(html));
            });
        }).on('error',(e)=>{
            reject(e);
        });
    });
    return p;
};

/**
 * 调用zlmediakit 进行截图操作
 */
Media.snap0=function(query,deviceid,channel){
    let p=new Promise(function(resolve,reject){
        let url = constants.zlmedia.url + 'index/api/getSnap';
        let param ="?" + query;
        let path = settingModel.cache.snap_path + "/" + deviceid + "_" + channel + ".jpg";
        request(url+param).pipe(fs.createWriteStream(path));
        resolve({});
    });
    return p;
};
/**
 * 使用fluent-ffmpeg截图
 */
Media.snap=function(source,deviceid,channel){

    let p = new Promise(function(resolve,reject){
        ffmpeg({source:source,timeout: 20})
            .on('filenames', function(filenames) {
                console.log('Will generate ' + filenames.join(', '))
                resolve(filenames);
            })
            .on('end', function() {
                console.log('ffmpeg end');
            })
            .on('stderr', function(stderrLine) {
                console.log('Stderr output: ' + stderrLine);
            })
            .on('error', function(err, stdout, stderr) {
                console.log('Cannot process video: error =' , err.message);
            }).
            addOption(['-rtsp_transport tcp'])
            .screenshots({
                count: 1,
                timestamps: ['0.5'],
                folder: settingModel.cache.snap_path ,
                filename: deviceid + "_" + channel + ".jpg",
                size: '640x?',
                timeout: 20
        });
    });
    return p;
    
};
module.exports=Media;